<?php 
//session_start(); 
include("helper/DBOperation.php");
include("alert_loader.php");
$dbObj = new DBOperation();
$datatype = $_REQUEST['datatype'];
$insert_keyvalue = array();
$message = array();
$color_status = array();
$stripColor	= array();
$stripColor[]	= "green";
$color = "green";
$allDataType = array("CPUH","CPUV","Displays","HVAC");
$error = 0;
$messagelog = "";

//0 - white
//1 - green
//2 - yellow
//3 - red
//4 - blue
$correctDataType = false;
$sql = $dbObj->executeQuery("SELECT component_name FROM tbl_components where id='".$_REQUEST['c_id']."' ORDER BY id DESC LIMIT 1", true);

switch($sql["component_name"]){
	case "CPUH": 
	case "CPUV":
		if($datatype == 1)
			$correctDataType = true;
		break;
	case "Displays":
		if($datatype == 3)
			$correctDataType = true;
		break;
 
	case "HVAC-H":
	case "HVAC-V":
		if($datatype == 2)
			$correctDataType = true;
		break;
	
}
if(!$correctDataType){
	//echo "Datatype and c_id doesn't match.";exit;
	$error = 1;
	$messagelog = "Datatype and c_id doesn't match.";
}

if($correctDataType && $datatype == 1) {

	$cpu_temp = str_replace("oF","", $_REQUEST['cpu_tmp']);
	
	if(is_numeric($cpu_temp) && (($cpu_temp < $cpuTempYellowLow) || ($cpu_temp > $cpuTempYellowHigh))) {
		$color_status[] = 2;
		$message[] = "temperature ".$cpu_temp ."<sup>o</sup>F";
		$color = "yellow";
		$stripColor[]	= "yellow";
	}
	
	$current_status = $_REQUEST['crnt_sts'];
	if($current_status== "offline" || $current_status== "") {
		$color_status[] = 3;
		$message[] = "shut down";
		$color = "red";
		$stripColor[]	= "red";
	}

	
	$cpu_temp = str_replace("oF","", $_REQUEST['cpu_tmp']);

	$network_speed = $_REQUEST['ntw_spd'];

	if(is_numeric($network_speed)) {
		if($network_speed < $ntwspdYellowHigh && $network_speed > $ntwspdYellowLow) {
			$color_status[] = 2;
			$message[] = "Network Speed ".$network_speed." Mbps";
			$color = "yellow";
			$stripColor[]	= "yellow";
		}elseif($network_speed == $ntwspdRed ) {
			$color_status[] = 3;
			$message[] = "Network Speed ".$network_speed." Mbps";
			$color = "red";
			$stripColor[]	= "red";
		}
	}

	$hd_space = $_REQUEST['hd_spc'];
	$free_hd_space = str_replace("GB","", $hd_space);

	if(is_numeric($free_hd_space)) {
		if($free_hd_space < $hdspaceYellowHigh &&  $free_hd_space >= $hdspaceYellowLow) {
			$color_status[] = 2;
			$message[] = "Free HD space ".$free_hd_space." GB";
			$color = "yellow";
			$stripColor[]	= "yellow";
		}elseif($free_hd_space < $hdspaceRed ) {
			$color_status[] = 3;
			$message[] = "Free HD space ".$free_hd_space." GB";
			$color = "red";
			$stripColor[]	= "red";
		}
	}
	
	// This is for finding out last ping.

 	  $sql = $dbObj->executeQuery("SELECT last_ping FROM tbl_component_cpu where component_id='".$_REQUEST['c_id']."' ORDER BY id DESC LIMIT 1", true);
	//echo "<pre>";print_r($sql);
  	//echo  date($sql['last_ping'])."<br>".date("Y-m-d h:i:s");
	if($sql['last_ping']){
	$currentPingTime 	= strtotime(date("Y-m-d H:i:s"));
	$lastPingTime		= strtotime($sql['last_ping']) ;
	$pingDifference		= $currentPingTime - $lastPingTime ;
	$pingDifference		= round($pingDifference/60);
	}else{
		$pingDifference = 0;
	}
	//minutes to hour minute	
	$hours          = floor($pingDifference / 60);
	$decimalMinutes = $pingDifference - floor($pingDifference/60) * 60;

	# Put it together.
	$hoursMinutes = sprintf("%dH%02.0fM", $hours, $decimalMinutes);
/*
	if($pingDifference >= $lastPingYellowCPU ) {
		if($pingDifference <= $lastPingRedCPU){
			$color_status[] = 2;
			$message[] =  "last ping was : ".$hoursMinutes." ago";
			$color = "yellow";
			$stripColor[]	= "yellow";
		}
		else{
			$color_status[] = 3;
			$message[] ="last ping was : ".$hoursMinutes." ago";
			$color = "red";
			$stripColor[]	= "red";
		}		
	}
		*/
	$color = "green";
	$stripColor[]	= "green";
	$red	= "0";
	$yellow	= "0";
	for($i=0;$i<count($stripColor);$i++){
		if($stripColor[$i]=="red"){
			$red	= "1";
		}		
	}
	if($red=="0"){
		for($i=0;$i<count($stripColor);$i++){
			if($stripColor[$i]=="yellow"){
				$yellow	= "1";
			}		
		}
	}

	if($red=="1"){
		$color	= "red";		
	}
	else if($yellow=="1"){
		$color	= "yellow";
	}
	else{
		$color	= "green";
	}
	
	//echo $color;exit;

	if(isset($_REQUEST['sch_fsze']) && $_REQUEST['sch_fsze']!=""){
		$sch_fsze = $_REQUEST['sch_fsze'];
	}else{
		$sch_fsze = "";
	}
	
	
	
	$insert_keyvalue['id'] = NULL;
	$insert_keyvalue['component_id'] = $_REQUEST['c_id'];
	$insert_keyvalue['component_type'] = $_REQUEST['c_tpe'];
	$insert_keyvalue['cpu_name'] = $_REQUEST['cpu_nme'];
	$insert_keyvalue['ip_address'] = $_REQUEST['ip_ad'];
	$insert_keyvalue['last_ping'] = date("Y-m-d H:i:s");
	$insert_keyvalue['current_status'] = $current_status;
	$insert_keyvalue['cpu_temp'] = $cpu_temp."<sup>o</sup>F";
	$insert_keyvalue['network_speed'] = $network_speed."Mbps";
	$insert_keyvalue['os_version'] = $_REQUEST['os_vrsn'];
	$insert_keyvalue['player_vers'] = $_REQUEST['plyr_vrs'];
	$insert_keyvalue['last_reboot'] = $_REQUEST['lst_rbt'];
	$insert_keyvalue['free_hd_space'] = $free_hd_space."GB";
	$insert_keyvalue['schedule_name'] = $_REQUEST['sch_nme'];
	$insert_keyvalue['last_sched_upload'] = $_REQUEST['lstschd_upld'];
	$insert_keyvalue['schedule_file_size'] = $sch_fsze;
	
	$dbObj->insertRecords('tbl_component_cpu',$insert_keyvalue);
	$unit_id = mysql_insert_id();
	
	if(count($message)>0) {
		for($msg=0;$msg<count($message); $msg++) {

			$insert_keyvalue_message = array();
			$insert_keyvalue_message['id'] = NULL;
			$insert_keyvalue_message['component_id'] = $_REQUEST['c_id'];
			$insert_keyvalue_message['unit_id'] = $unit_id;
			$insert_keyvalue_message['created_date'] = date("Y-m-d H:i:s");
			$insert_keyvalue_message['message'] = $message[$msg];
			$insert_keyvalue_message['status'] = $color_status[$msg];
			$dbObj->insertRecords('tbl_log_message', $insert_keyvalue_message);
		}
	}
	$insert_keyvalue_state = array();
	
	$insert_keyvalue_state['id'] = NULL;
	$insert_keyvalue_state['component_id'] = $_REQUEST['c_id'];
	$insert_keyvalue_state['state'] = $color;
	$insert_keyvalue_state['datetime'] = date("Y-m-d H:i:s");
	
	$dbObj->insertRecords('tbl_component_state',$insert_keyvalue_state);
    	//echo "Value Stored";
	
	$error = 0;
	$messagelog = "Values for Datatype ".$datatype." Stored.";

}elseif($correctDataType && $datatype == 2) {
	//HVAC
	// This is for finding out last ping.

 	  $sql = $dbObj->executeQuery("SELECT last_ping FROM tbl_component_hvac where component_id='".$_REQUEST['c_id']."' ORDER BY id DESC LIMIT 1", true);
	//echo "<pre>";print_r($sql);exit;

	$red	= "0";
	$yellow	= "0";
  	//echo  date($sql['last_ping'])."<br>".date("Y-m-d h:i:s");
	if($sql['last_ping']){
	$currentPingTime 	= strtotime(date("Y-m-d H:i:s"));
	$lastPingTime		= strtotime($sql['last_ping']) ;
	$pingDifference		= $currentPingTime - $lastPingTime ;
	$pingDifference		= round($pingDifference/60);
	}else{
		$pingDifference = 0;
	}
	//minutes to hour minute	
	$hours          = floor($pingDifference / 60);
	$decimalMinutes = $pingDifference - floor($pingDifference/60) * 60;

	# Put it together.
	$hoursMinutes = sprintf("%dH%02.0fM", $hours, $decimalMinutes);
/*
	if($pingDifference >= $lastPingYellowHVAC ) {
		if($pingDifference <= $lastPingRedHVAC){
			$color_status[] = 2;
			$message[] =  "last ping was : ".$hoursMinutes." ago";
			$color = "yellow";
			$stripColor[]	= "yellow";
		}
		else{
			$color_status[] = 3;
			$message[] ="last ping was : ".$hoursMinutes." ago";
			$color = "red";
			$stripColor[]	= "red";
		}		
	}
	*/
		$color = "green";
		$stripColor[]	= "green";


	$hvac_in_temp = str_replace("oF","", $_REQUEST['in_tmp']);
	if(is_numeric($hvac_in_temp) && (($hvac_in_temp < $inTempYellowLow) || ($hvac_in_temp > $inTempYellowHigh))) {
		$color_status[] = 2;
		$message[] = "Inside Temperature ".$hvac_in_temp ."<sup>o</sup>F";
		$stripColor[]	= "yellow";
		$color = "yellow";
	}

	$hvac_out_temp = str_replace("oF","", $_REQUEST['out_tmp']);
	if(is_numeric($hvac_out_temp) && (($hvac_out_temp < $outTempYellowLow) || ($hvac_out_temp > $outTempYellowHigh))) {
		$color_status[] = 2;
		$message[] = "Outside Temperature ".$hvac_out_temp ."<sup>o</sup>F";
		$stripColor[]	= "yellow";
		$color = "yellow";
	}
	
	$hvac_water_present = $_REQUEST['water'];
	if($hvac_water_present == "yes") {
		$color_status[] = 2;
		$message[] = "Water Present";
		$stripColor[]	= "yellow";
		$color = "yellow";
	}


	$hvac_inside_humidity = str_replace("%","", $_REQUEST['in_hmdity']);
	if(is_numeric($hvac_inside_humidity) &&  (($hvac_inside_humidity > $inHumidityYellowHigh)||($hvac_inside_humidity < $inHumidityYellowLow))) {
		$color_status[] = 2;
		$message[] = "Inside Humidity ".$hvac_inside_humidity ."%";
		$stripColor[]	= "yellow";
		$color = "yellow";
	}


	
	$red	= "0";
	$yellow	= "0";
	for($i=0;$i<count($stripColor);$i++){
		if($stripColor[$i]=="red"){
			$red	= "1";
		}		
	}
	if($red=="0"){
		for($i=0;$i<count($stripColor);$i++){
			if($stripColor[$i]=="yellow"){
				$yellow	= "1";
			}		
		}
	}

	if($red=="1"){
		$color	= "red";		
	}
	else if($yellow=="1"){
		$color	= "yellow";
	}
	else{
		$color	= "green";
	}
	

	$insert_keyvalue['id'] = NULL;
	$insert_keyvalue['component_id'] = $_REQUEST['c_id'];
	$insert_keyvalue['hvac_unit_name'] = $_REQUEST['hvac_unme'];
	$insert_keyvalue['controller_firmware_ver'] = $_REQUEST['clr_frm'];
	$insert_keyvalue['ac_status'] = $_REQUEST['ac_sts'];
	$insert_keyvalue['heater_status'] = $_REQUEST['hetr_sts'];
	$insert_keyvalue['water_present'] = $hvac_water_present;
	$insert_keyvalue['inside_temp'] = $hvac_in_temp."<sup>o</sup>F";
	$insert_keyvalue['outside_temp'] = $hvac_out_temp."<sup>o</sup>F";
	$insert_keyvalue['inside_humidity'] = $hvac_inside_humidity."%";
	$insert_keyvalue['last_ping'] = date("Y-m-d H:i:s");
	
	$dbObj->insertRecords('tbl_component_hvac',$insert_keyvalue);
	$unit_id = mysql_insert_id();

	if(count($message)>0) {
		for($msg=0;$msg<count($message); $msg++) {
			$insert_keyvalue_message = array();
			$insert_keyvalue_message['id'] = NULL;
			$insert_keyvalue_message['component_id'] = $_REQUEST['c_id'];
			$insert_keyvalue_message['unit_id'] = $unit_id;
			$insert_keyvalue_message['created_date'] = date("Y-m-d H:i:s");
			$insert_keyvalue_message['message'] = $message[$msg];
			$insert_keyvalue_message['status'] = $color_status[$msg];
			$dbObj->insertRecords('tbl_log_message', $insert_keyvalue_message);
			
		}
	}
	$insert_keyvalue_state = array();
	
	$insert_keyvalue_state['id'] = NULL;
	$insert_keyvalue_state['component_id'] = $_REQUEST['c_id'];
	$insert_keyvalue_state['state'] = $color;
	$insert_keyvalue_state['datetime'] = date("Y-m-d H:i:s");
	
	$dbObj->insertRecords('tbl_component_state',$insert_keyvalue_state);
	//echo "Value Stored";

	$error = 0;
	$messagelog = "Values for Datatype ".$datatype." Stored.";

}elseif($correctDataType && $datatype == 3){

//Display

	$current_status = $_REQUEST['crnt_sts'];
	if($current_status== "offline" || $current_status== "") {
		$color_status[] = 3;
		$message[] = "shut down";
		$stripColor[] = "red";
		$color = "red";
	}	

	$dis_temp = str_replace("oF","", $_REQUEST['ds_tmp']);
	if(is_numeric($dis_temp) && (($dis_temp < $disTempYellowLow) || ($dis_temp > $disTempYellowHigh))) {
		$color_status[] = 2;
		$message[] = "display temperature ".$dis_temp;
		$stripColor[]	= "yellow";
		$color = "yellow";
	}

	$dis_bk_temp = str_replace("oF","", $_REQUEST['bk_tmp']);
	if(is_numeric($dis_bk_temp) && (($dis_bk_temp < $backTempYellowLow) || ($dis_bk_temp > $backTempYellowHigh))) {
		$color_status[] = 2;
		$message[] = "backlight temperature ".$dis_bk_temp ."<sup>o</sup>F";
		$stripColor[]	= "yellow";
		$color = "yellow";
	}

	$dis_ctrl_temp = str_replace("oF","", $_REQUEST['ctrlbrd_tmp']);
	if(is_numeric($dis_ctrl_temp) && (($dis_ctrl_temp < $ctrlTempYellowLow) || ($dis_ctrl_temp > $ctrlTempYellowHigh))) {
		$color_status[] = 2;
		$message[] = "control board temperature ".$dis_ctrl_temp ."<sup>o</sup>F";
		$stripColor[]	= "yellow";
		$color = "yellow";
	}
	

	$dis_dty_cycle = str_replace("%","", $_REQUEST['dty_cyle']);
	if($dis_dty_cycle < $dutyCycleYellow) {
		$color_status[] = 2;
		$message[] = "Duty Cycle ".$dis_dty_cycle ."%";
		$stripColor[]	= "yellow";
		$color = "yellow";
	}
	
	$dis_brght = str_replace("%","", $_REQUEST['brght']);
	
	if(is_numeric($dis_brght)){
		
		if(($dis_brght >=$dispBrightYellowLow) && ($dis_brght < $dispBrightYellowHigh)){
		
		$color_status[] = 2;
		$message[] = "Brightness ".$dis_brght;
		$stripColor[]	= "yellow";
		$color = "yellow";
	}
	elseif($dis_brght<$dispBrightRed){
		
		$color_status[] = 3;
		$message[] = "Brightness ".$dis_brght;
		$color = "red";
		$stripColor[]	= "red";
	}

	
	
}

// Red - <5%
// Yellow - >5% & <20%
// Green - >20%
// This is for finding out last ping.

 	  $sql = $dbObj->executeQuery("SELECT last_ping FROM tbl_component_display where component_id='".$_REQUEST['c_id']."' ORDER BY id DESC LIMIT 1", true);
	//echo "<pre>";print_r($sql);exit;

  	//echo  date($sql['last_ping'])."<br>".date("Y-m-d h:i:s");
	if($sql['last_ping']){
	$currentPingTime 	= strtotime(date("Y-m-d H:i:s"));
	$lastPingTime		= strtotime($sql['last_ping']) ;
	$pingDifference		= $currentPingTime - $lastPingTime ;
	$pingDifference		= round($pingDifference/60);
	}else{
		$pingDifference = 0;
	}
	//minutes to hour minute	
	$hours          = floor($pingDifference / 60);
	$decimalMinutes = $pingDifference - floor($pingDifference/60) * 60;

	# Put it together.
	$hoursMinutes = sprintf("%dH%02.0fM", $hours, $decimalMinutes);
/*
	if($pingDifference >= $lastPingYellowDisplay ) {
		if($pingDifference <= $lastPingRedDisplay){
			$color_status[] = 2;
			$message[] =  "last ping was : ".$hoursMinutes." ago";
			$color = "yellow";
			$stripColor[]	= "yellow";
		}
		else{
			$color_status[] = 3;
			$message[] ="last ping was : ".$hoursMinutes." ago";
			$color = "red";
			$stripColor[]	= "red";
		}		
	}
*/
$color = "green";
$stripColor[]	= "green";		

	$red	= "0";
	$yellow	= "0";
	for($i=0;$i<count($stripColor);$i++){
		if($stripColor[$i]=="red"){
			$red	= "1";
		}		
	}
	if($red=="0"){
		for($i=0;$i<count($stripColor);$i++){
			if($stripColor[$i]=="yellow"){
				$yellow	= "1";
			}		
		}
	}

	if($red=="1"){
		$color	= "red";		
	}
	else if($yellow=="1"){
		$color	= "yellow";
	}
	else{
		$color	= "green";
	}
	

	if($_REQUEST['ds_tpe']!="" && $_REQUEST['ds_tpe']<5){
	$insert_keyvalue['id'] = NULL;
	$insert_keyvalue['component_id'] = $_REQUEST['c_id'];
	$insert_keyvalue['display_type'] = $_REQUEST['ds_tpe'];
	$insert_keyvalue['display_name'] = $_REQUEST['ds_nme'];
	$insert_keyvalue['ip_address'] = $_REQUEST['ip_ad'];
	$insert_keyvalue['last_ping'] = date("Y-m-d H:i:s");
	$insert_keyvalue['current_status'] = $current_status;
	$insert_keyvalue['display_temp'] = $dis_temp;
	$insert_keyvalue['backlight_temp'] = $dis_bk_temp."<sup>o</sup>F";
	$insert_keyvalue['ctrl_board_temp'] = $dis_ctrl_temp."<sup>o</sup>F";
	$insert_keyvalue['duty_cycle'] = $dis_dty_cycle."%";
	$insert_keyvalue['ambient_light'] = $_REQUEST['ambnt_lght']."%";
	$insert_keyvalue['brightness'] =$dis_brght;
	$insert_keyvalue['input_source'] = $_REQUEST['inpt_srce'];
//echo "<pre>";print_r($_REQUEST['ambnt_lght']."%");exit;
	
	$dbObj->insertRecords('tbl_component_display',$insert_keyvalue);
	$unit_id = mysql_insert_id();

	if(count($message)>0) {
		for($msg=0;$msg<count($message); $msg++) {

			$insert_keyvalue_message = array();
			$insert_keyvalue_message['id'] = NULL;
			$insert_keyvalue_message['component_id'] = $_REQUEST['c_id'];
			$insert_keyvalue_message['unit_id'] = $unit_id;
			$insert_keyvalue_message['created_date'] = date("Y-m-d H:i:s");
			$insert_keyvalue_message['message'] = $message[$msg];
			$insert_keyvalue_message['status'] = $color_status[$msg];
			//echo "<pre>";print_r($color_status[$msg]);
			$dbObj->insertRecords('tbl_log_message', $insert_keyvalue_message);
		}
	}
	$insert_keyvalue_state = array();

	
	
	$insert_keyvalue_state['id'] = NULL;
	$insert_keyvalue_state['component_id'] = $_REQUEST['c_id'];
	$insert_keyvalue_state['state'] = $color;
	$insert_keyvalue_state['datetime'] = date("Y-m-d H:i:s");
	
	$dbObj->insertRecords('tbl_component_state',$insert_keyvalue_state);
	
	//echo "Value Stored";
	$error = 0;
	$messagelog = "Values for Datatype ".$datatype." Stored.";
	}else{
		//echo "Display Type is not correct";
		$error = 1;
		$messagelog = "Display Type is not correct for Datatype ".$datatype;
	}
}

$error_log = array("Error"   => $error,
	           "Message" => $messagelog);

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($error_log);

?>
